package com.dykj.fireFighting.web.cron;

import com.dykj.fireFighting.api.base.appNotification.PushModel;
import com.dykj.fireFighting.api.base.push.service.PushService;
import com.dykj.fireFighting.api.fire.contractMessage.entity.ContractMessage;
import com.dykj.fireFighting.api.fire.contractMessage.service.IContractMessageService;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.dto.ContractNotifyRecordPushDto;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.entity.ContractNotifyRecord;
import com.dykj.fireFighting.api.fire.contractNotifyRecord.service.IContractNotifyRecordService;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Component
public class ContractNotifyTimmer {

    // 保存任务
    private Map<String, ScheduledFuture<?>> futuresMap = new ConcurrentHashMap<String, ScheduledFuture<?>>();
    @DubboReference
    private IContractNotifyRecordService contractNotifyRecordService;
    @DubboReference
    private IContractMessageService iContractMessageService;


    // 创建ThreadPoolTaskScheduler线程池
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @DubboReference
    private PushService pushService;


    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(20);
        //threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        return threadPoolTaskScheduler;
    }

    // 初始化任务
    @Bean
    public void initTimmer() {
        List<ContractNotifyRecord> list = contractNotifyRecordService.queryUnDoneList();
        for (ContractNotifyRecord s : list) {
            try {
                ContractNotifyRecordPushDto pushDto=new ContractNotifyRecordPushDto();
                BeanUtils.copyProperties(pushDto,s);
                ContractMessage contractMessage=iContractMessageService.getById(s.getContractId());
                if(s.getType()==1)
                {
                    pushDto.setTitle("合同到期通知");
                    pushDto.setBody("维保合同号:"+contractMessage.getContractNumber()+"的合同即将到期，请注意查看");
                }else{
                    pushDto.setTitle("付款提醒通知");
                    pushDto.setBody("维保合同号:"+contractMessage.getContractNumber()+"的合同需要付款了，请注意查看");
                }
               pushDto.setClickType("none");

                LocalDateTime localReleaseTime = DateUtil.asLocalDateTime(s.getNoticeTime());
                if (localReleaseTime.isAfter(LocalDateTime.now())) {
                    ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(getRunnable(pushDto), getTrigger(pushDto));
                    futuresMap.put(s.getId(), future);
                }

            }catch (Exception e)
            {
                e.printStackTrace();
            }



        }
    }




    /**
     * 删除/暂停任务
     *
     * @param key
     * @return
     */
    public boolean pauseeTask(String key) {
        ScheduledFuture toBeRemovedFuture = futuresMap.remove(key);
        if (toBeRemovedFuture != null) {
            toBeRemovedFuture.cancel(true);
            // log.info("删除/暂停任务*************>定时任务id={},", key);
            return true;
        } else {
            return false;
        }
    }


    /**
     * 执行方法
     *
     * @param contractNotifyRecordPushDto
     * @return
     */
    private Runnable getRunnable(ContractNotifyRecordPushDto contractNotifyRecordPushDto) {
        return new Runnable() {
            @Override
            public void run() {
                //    log.info("开始执行定时任务------->定时任务id={},定时任务code={},定时任务cron={},", taskScheduling.getId(), taskScheduling.getCode(), taskScheduling.getReleaseTime());
                //taskSchedulingService.releaseTask(contractNotifyRecord.getId());
                //只执行一次
                PushModel pushModel=new PushModel();
                try {
                    BeanUtils.copyProperties(pushModel,contractNotifyRecordPushDto);

                }catch (Exception e)
                {
                    e.printStackTrace();
                }


                pushService.pushAlias(pushModel);

                pauseeTask(contractNotifyRecordPushDto.getId());
//                if (taskScheduling.getType() == 0) {
//                    //随机任务执行后删除下次任务
//                    pauseeTask(taskScheduling.getId());
//                }
            }
        };
    }

    /**
     * 触发器
     *
     * @param contractNotifyRecordPushDto
     * @return
     */
    private Trigger getTrigger(ContractNotifyRecordPushDto contractNotifyRecordPushDto) {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {

                LocalDateTime localDateTime = DateUtil.asLocalDateTime(contractNotifyRecordPushDto.getNoticeTime());
                ZoneId zone = ZoneId.systemDefault();
                Instant instant = localDateTime.atZone(zone).toInstant();
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //log.info("添加定时任务+++++++++>定时任务id={},定时任务code={},定时任务执行时间={}", taskScheduling.getId(), taskScheduling.getCode(), sdf.format(Date.from(instant)));
                return Date.from(instant);
            }


        };
    }
}
